package com.tang4j.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tang4j.core.exception.ValidateException;
import com.tang4j.core.model.ResponseModel;
import com.tang4j.core.model.easyui.TreeGrid;
import com.tang4j.core.model.factory.ResponseModelFactory;
import com.tang4j.core.service.impl.AbstractServiceImpl;
import com.tang4j.core.util.DataUtil;
import com.tang4j.mapper.ThSysRoleMapper;
import com.tang4j.model.ThSysNavigationRoleInfo;
import com.tang4j.model.ThSysRole;
import com.tang4j.model.factory.RoleFactory;
import com.tang4j.service.ThSysNavigationRoleInfoService;
import com.tang4j.service.ThSysRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 * 角色表 服务实现类
 * </p>
 *
 * @author saber
 * @since 2019-11-18
 */
@Service
public class ThSysRoleServiceImpl extends AbstractServiceImpl<ThSysRoleMapper, ThSysRole> implements ThSysRoleService {

    @Autowired
    private ThSysNavigationRoleInfoService navigationRoleInfoService;

    @Override
    public ResponseModel getRoles() {
        try {
            List<ThSysRole> thSysRoleList = this.queryList(new QueryWrapper<>());
            if (thSysRoleList != null) {
                List<TreeGrid> treeGridList = RoleFactory.createTreeGridList(thSysRoleList);
                return ResponseModelFactory.OKWithData(treeGridList);
            } else {
                throw new ValidateException("未读取到有效角色信息");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseModelFactory.error(e.getMessage());
        }

    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public ThSysRole update(ThSysRole thSysRole) {
        ThSysRole tempRole = super.update(thSysRole);
        if (DataUtil.isEmpty(tempRole.getId())) {
            throw new ValidateException("新增角色后未读取到有效角色id,无法绑定菜单");
        } else {
            if (DataUtil.isEmpty(thSysRole.getId())) {
                this.navigationRoleInfoService.update(new ThSysNavigationRoleInfo(tempRole.getId(), thSysRole.getNavigationId()));
            }
        }
        return tempRole;
    }

}
